﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using System.Data;
using Wheeler.Common.Extensions;
using Wheeler.Domain;
using Wheeler.Web.ViewModels;
using Wheeler.Web.Utility;
using AutoMapper;
using Wheeler.Web.ViewModels.UtilityModels;

namespace Wheeler.Web.Areas.Private.Controllers
{
    [Authorize(Roles = "Operator,Admin")]
    public class VehicleController : BaseController
    {
		private WheelerEntities _Context = new WheelerEntities();
        
		#region Constructors
		public VehicleController()
		{
		}

		public VehicleController(UserViewModel currentUser)
			: base(currentUser)
        {
        }
		#endregion Constructors

		#region Action Methods

        public ActionResult Index()
        {
            return RedirectToAction("Search");
        }

		/// <summary>
        /// Gets a Vehicle from Database to edit
        /// </summary>
        /// <param name="id"></param>
        /// <returns></returns>
		public ActionResult Edit(int id = 0, String IsSaved = null)
        {   
            Vehicle entity = id == 0 ? new Vehicle() : _Context.Vehicles.Include("TestResults").FirstOrDefault(P => P.ID == id);            
            VehicleViewModel viewModel = Mapper.Map<Vehicle, VehicleViewModel>(entity);
            if (entity != null && entity.TestResults.Count > 0)
                viewModel.HasPublished = entity.TestResults.ToList()[0].HasPublished;

            if (String.Compare(IsSaved, "true", true) == 0)
                ViewData[AppConstants.ViewDataKeys.SAVED] = true;
			return View(viewModel);
        }

		/// <summary>
        /// Saves Vehicle Information into the Database
        /// </summary>
        /// <param name="viewModel"></param>
        /// <returns></returns>
		[HttpPost]
		public ActionResult Edit(VehicleViewModel viewModel)
        {
			if (!ModelState.IsValid)
                return View(viewModel);

            FixedVehicle fixedVehicle = _Context.GetFixedVehicle(viewModel.RegistrationNo, viewModel.ChasisNo, viewModel.EngineNo);
            bool hasValidationError = false;

            if (_Context.IsDuplicateRegistrationNumber(viewModel.RegistrationNo, viewModel.ID))
            {
                ModelState.AddModelError("RegistrationNo", "This Registration number already exists!");
                hasValidationError = true;                
            }
            if (_Context.IsDuplicateEngineNumber(viewModel.EngineNo, viewModel.ID))
            {
                ModelState.AddModelError("EngineNo", "This Engine Number already exists!");
                hasValidationError = true;
            }
            if (_Context.IsDuplicateChasisNumber(viewModel.ChasisNo, viewModel.ID))
            {
                ModelState.AddModelError("ChasisNo", "This Chasis Number already exists!");
                hasValidationError = true;
            }
            if (_Context.IsDuplicateCylinderNumber(viewModel.CNGCylinderNo, viewModel.ID))
            {
                ModelState.AddModelError("CNGCylinderNo", "This CNG Cylinder Number already exists!");
                hasValidationError = true;
            }
            if (_Context.IsDuplicateBRTANumber(viewModel.BRTANumber, viewModel.ID))
            {
                ModelState.AddModelError("BRTANumber", "This BRTA Number already exists!");
                hasValidationError = true;
            }
            if (fixedVehicle == null)
            {
                ModelState.AddModelError("RegistrationEngineChassis", "This auto rickshaw does not exist in BRTA database! Check the Registration Number, Engine Number and Chassis Number");
                hasValidationError = true;
            }
            if(hasValidationError)
                return View(viewModel);

            ///TODO: Check for existance of the vehicle in the FixedVehicle table from BRTA
            
			Vehicle entity = null;
            ///We don't want to changes the teststatus by any malicious user
            //DbObject.TestStatus testStatus = DbObject.TestStatus.NOT_TESTED;

            if (viewModel.ID == 0)
            {
                entity = new Vehicle();
                _Context.AddToVehicles(entity);
            }
            else
            {
                entity = _Context.Vehicles.FirstOrDefault(P => P.ID == viewModel.ID);
                ///We don't want to changes the teststatus by any malicious user
                //viewModel.TestStatus = testStatus = entity.TestStatus == 0 ? DbObject.TestStatus.NOT_TESTED : (DbObject.TestStatus) entity.TestStatus;
            }

            entity = Mapper.Map<VehicleViewModel, Vehicle>(viewModel, entity);
            if (viewModel.ID == 0)
            {
                entity.CreatedOn = DateTime.Now;
                ///TODO: Need to judge this, for the time being setting default values;
                entity.IsVerified = true;
                entity.FixedVehicleID = fixedVehicle.ID;
                entity.CreatedBy = LoggedInUser.ID;                
            }
            //entity.TestStatus = (int)testStatus;
            entity.ModifiedBy = base.LoggedInUser.ID;
            entity.ModifiedOn = DateTime.Now;
		
            _Context.SaveChanges();
            //return RedirectToAction("Index");
			return RedirectToAction(String.Format("Edit/{0}", entity.ID), new { IsSaved = "true" });
        }

        public ActionResult Search(String registrationNo = null, String viewType = null, int pageNo = 0)
        {
            viewType = viewType.IsEmpty() ? ConfigReader.DefaultViewForSearchResults : viewType;

            TestResultSearchModel searchModel = new TestResultSearchModel(registrationNo.UrlDecode(), String.Empty, String.Empty, viewType.UrlDecode());
            ViewData[AppConstants.ViewDataKeys.SEARCH_KEY] = searchModel;

            if (searchModel.HasKeys)
            {
                UtilityDAO dao = new UtilityDAO();
                Wheeler.Domain.DbParameter[] parameters = new[] { new Wheeler.Domain.DbParameter("RegistrationNo", searchModel.RegistrationNo) };

                int totalRecord = 0;
                pageNo = pageNo == 0 ? 1 : pageNo;
                DataSet ds = dao.GetPagedData(DbObject.SP.GET_VEHICLE_LIST, parameters, pageNo, ConfigReader.PageSize, out totalRecord, true);               

                ViewModels.UtilityModels.PagerConfig pagerConfig = new ViewModels.UtilityModels.PagerConfig(pageNo, ConfigReader.PageSize, totalRecord);
                ListConfig listConfig = new ListConfig(ds.Tables[0], pagerConfig);
                return View(listConfig);
            }
            return View();
        }

        [HttpPost]
        public ActionResult Search(TestResultSearchModel viewModel, int pageNo = 0)
        {
            return RedirectToAction("Search", new { RegistrationNo = viewModel.RegistrationNo.UrlEncode(), ViewType = viewModel.ViewType.UrlEncode(), PageNo = pageNo });
        }
		#endregion Action Methods
		
		#region Helper Methods

        #endregion			
    }
}


